package thread;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2024-09-28
 * Time: 10:19
 */
class MyThreadPollExecutor{
    //4:创建一个顺序表存放一下线程数目，方便后续代码功能的增添
    private LinkedList<Thread> threadList = new LinkedList<>();
    //private List<Thread> threadList2 = new ArrayList<>();

    //创建一个阻塞队列放任务
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);

    //1:提供构造方法，指定我们要创建的线程的数目
    public MyThreadPollExecutor(int n){
        for(int i = 0 ; i < n ; i++){
            //2:在构造方法中，把线程创建好
            Thread t = new Thread(()->{
                //3:执行任务
                while(true){
                    try {
                        //注意点1：poll方法是带有超时间的take，take是死等
                        Runnable runnable = queue.take();
                        runnable.run();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            //5:把t线程扔到顺序表里
            threadList.offer(t);
            t.start();
        }


    }
    //6:提供submit方法，把任务放到队列里面
    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);//注意点3：表是offer，队列是put
    }
}
public class ThreadDemon35_2 {
    public static void main(String[] args) throws InterruptedException {
        //7:怎么在main方法中利用好上述Executor呢
        //8:先实例化类，定好创建线程的数目
        MyThreadPollExecutor executor = new MyThreadPollExecutor(5);
        //9:创建任务用submit提交进队列
        for (int i = 0; i < 100; i++) {
            //注意点2：变量捕获
            int n = i;
            executor.submit(new Runnable() {
                //每写一遍都有一遍新的收获。
                @Override
                public void run() {
                    System.out.println("线程" + Thread.currentThread().getName() + "  " + "正在执行任务" + n);
                }
            });
        }
    }

}
